package com.facebook.android;

import java.io.ByteArrayOutputStream;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.SessionEvents.AuthListener;
import com.facebook.android.SessionEvents.LogoutListener;
import com.multitrack.main.R;
import com.multitrack.map.TrackMapActivity;

public class CustomFacebook {
	// 캡쳐하기 부분 시작

	final static int AUTHORIZE_ACTIVITY_RESULT_CODE = 0;
	private Activity activity;
	private ProgressDialog mProgress;
	private String[] permissions = { "offline_access", "publish_stream",
			"user_photos", "publish_checkins", "photo_upload" };

	public CustomFacebook(Activity activity) {
		this.activity = activity;
		Utility.mFacebook = new Facebook(activity.getResources().getString(
				R.string.facebook_app_id));
	}

	public void login() {
		SessionListener mSessionListener = new SessionListener();
		SessionEvents.addAuthListener(mSessionListener);
		Utility.mFacebook.authorize(activity, permissions,
				AUTHORIZE_ACTIVITY_RESULT_CODE, new LoginDialogListener());

	}

	public void logout() {
		mProgress = new ProgressDialog(activity);
		mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		mProgress.setTitle("처리 중");
		mProgress.setMessage("Wait...");
		mProgress.setCancelable(false);
		mProgress.show();
		SessionListener mSessionListener = new SessionListener();
		SessionEvents.addLogoutListener(mSessionListener);
		SessionEvents.onLogoutBegin();
		AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(
				Utility.mFacebook);
		asyncRunner.logout(activity, new LogoutRequestListener());
	}

	public boolean screenCapture(View v) {
		mProgress = new ProgressDialog(activity);
		mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		mProgress.setTitle("처리 중");
		mProgress.setMessage("Wait...");
		mProgress.setCancelable(false);
		mProgress.show();

		SessionStore.restore(Utility.mFacebook, activity);
		if (Utility.mFacebook.isSessionValid()) {
			Log.d("facebook", "로그인 성공1");
			// requestUserData();
		} else {
			// Log.d("facebook", "세션 없음");
			Utility.mFacebook.authorize(activity, permissions,
					AUTHORIZE_ACTIVITY_RESULT_CODE, new LoginDialogListener());
			if (mProgress != null && mProgress.isShowing()) {
				mProgress.dismiss();
			}
			// Util.showAlert(this, "Warning",
			// "You must first log in.");
		}

		if (Utility.mFacebook.isSessionValid()) {
			Log.d("facebook", "로그인 성공2");
			Utility.mAsyncRunner = new AsyncFacebookRunner(Utility.mFacebook);
			SessionEvents.addAuthListener(new FbAPIsAuthListener());
			v.setWillNotCacheDrawing(false);
			v.destroyDrawingCache();
			v.buildDrawingCache();

			Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
			Bundle params = new Bundle();
			if (bitmap != null) {
				params.putByteArray("photo", bitmapToByteArray(bitmap));
				params.putString("caption", "FbAPIs Sample App photo upload");
				Utility.mAsyncRunner.request("me/photos", params, "POST",
						new PhotoUploadListener(), null);
			} else {
				Log.d("facebook", "이미지 추출 실패");
				return false;
			}

		} else {
			Log.d("facebook", "로그인 실패");
			return false;
		}
		return true;
	}

	private class SessionListener implements AuthListener, LogoutListener {

		public void onAuthSucceed() {
			// setImageResource(R.drawable.logout_button);
			SessionStore.save(Utility.mFacebook, activity);
		}

		public void onAuthFail(String error) {
		}

		public void onLogoutBegin() {
		}

		public void onLogoutFinish() {
			SessionStore.clear(activity);

			// setImageResource(R.drawable.login_button);
		}
	}

	private class LogoutRequestListener extends BaseRequestListener {
		Handler mHandler = new Handler();

		public void onComplete(String response, final Object state) {
			/*
			 * callback should be run in the original thread, not the background
			 * thread
			 */
			mHandler.post(new Runnable() {
				public void run() {
					if (mProgress != null && mProgress.isShowing()) {
						mProgress.dismiss();
					}
					SessionEvents.onLogoutFinish();
				}
			});
		}
	}

	private final class LoginDialogListener implements DialogListener {
		public void onComplete(Bundle values) {

			SessionEvents.onLoginSuccess();
		}

		public void onFacebookError(FacebookError error) {

			SessionEvents.onLoginError(error.getMessage());
		}

		public void onError(DialogError error) {

			SessionEvents.onLoginError(error.getMessage());
		}

		public void onCancel() {

			SessionEvents.onLoginError("Action Canceled");
		}

	}

	public class FbAPIsAuthListener implements AuthListener {

		public void onAuthSucceed() {
			// requestUserData();
		}

		public void onAuthFail(String error) {
			// mText.setText("Login Failed: " + error);
		}
	}

	public class UserRequestListener extends BaseRequestListener {
		private Handler mHandler = new Handler();

		public void onComplete(final String response, final Object state) {
			JSONObject jsonObject;
			try {
				jsonObject = new JSONObject(response);

				final String picURL = jsonObject.getString("picture");
				final String name = jsonObject.getString("name");
				Utility.userUID = jsonObject.getString("id");

				mHandler.post(new Runnable() {
					public void run() {
						// mText.setText("Welcome " + name + "!");
						// mUserPic.setImageBitmap(Utility.getBitmap(picURL));
					}
				});

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	public static byte[] bitmapToByteArray(Bitmap bitmap) {

		ByteArrayOutputStream stream = new ByteArrayOutputStream();

		bitmap.compress(CompressFormat.JPEG, 100, stream);

		byte[] byteArray = stream.toByteArray();

		return byteArray;

	}

	public class PhotoUploadListener extends BaseRequestListener {

		private Handler mHandler = new Handler();

		public void onComplete(final String response, final Object state) {
			if (mProgress != null && mProgress.isShowing()) {
				mProgress.dismiss();
			}
			mHandler.post(new Runnable() {
				public void run() {
					new UploadPhotoResultDialog(activity,
							"Upload Photo executed", response).show();
				}
			});
		}

		public void onFacebookError(FacebookError error) {
			if (mProgress != null && mProgress.isShowing()) {
				mProgress.dismiss();
			}
			Toast.makeText(activity, "Facebook Error: " + error.getMessage(),
					Toast.LENGTH_LONG).show();
		}
	}

	// 캡쳐하기 부분 끝
}
